<?php

namespace app\service;

use app\model\Account;
use app\model\Category;
use app\model\UserLog;
use app\service\EncryptionService;
use Exception;

class AccountService
{
    /**
     * 获取用户账号列表
     */
    public function getUserAccounts($userId, $filters = [])
    {
        $categoryId = $filters['category_id'] ?? null;
        $keyword = $filters['keyword'] ?? null;
        $isFavorite = $filters['is_favorite'] ?? null;

        // 使用预加载避免N+1查询
        $accounts = Account::getUserAccounts($userId, $categoryId, $keyword, $isFavorite)
            ->with(['category'])  // 预加载分类关系
            ->select();

        return $accounts->toArray();
    }

    /**
     * 获取账号详情
     */
    public function getAccountDetail($userId, $accountId)
    {
        $account = Account::where('id', $accountId)
            ->where('user_id', $userId)
            ->with(['category'])
            ->find();

        if (!$account) {
            throw new Exception('账号不存在');
        }

        // 记录查看日志
        UserLog::record($userId, 'view_account', "查看账号: {$account->title}", 'account', $accountId);

        // 更新最后使用时间
        $account->updateLastUsed();

        return $account->toArray();
    }

    /**
     * 验证主密码并获取解密的账号详情
     */
    public function getDecryptedAccountDetail($userId, $accountId, $masterPassword)
    {
        // 先获取用户信息验证主密码
        $user = \app\model\User::find($userId);
        if (!$user) {
            throw new Exception('用户不存在');
        }

        // 验证主密码
        if (!$user->checkMasterPassword($masterPassword)) {
            throw new Exception('主密码错误');
        }

        $account = Account::where('id', $accountId)
            ->where('user_id', $userId)
            ->with(['category'])
            ->find();

        if (!$account) {
            throw new Exception('账号不存在');
        }

        // 解密敏感数据
        $accountArray = $account->toArray();

        try {
            if (!empty($account->username_encrypted)) {
                $accountArray['username'] = EncryptionService::decrypt(
                    $account->username_encrypted,
                    $account->encrypt_method ?? 'AES-256-GCM'
                );
            }

            if (!empty($account->password_encrypted)) {
                $accountArray['password'] = EncryptionService::decrypt(
                    $account->password_encrypted,
                    $account->encrypt_method ?? 'AES-256-GCM'
                );
            }

            if (!empty($account->notes_encrypted)) {
                $accountArray['notes'] = EncryptionService::decrypt(
                    $account->notes_encrypted,
                    $account->encrypt_method ?? 'AES-256-GCM'
                );
            }
        } catch (Exception $e) {
            throw new Exception('解密失败: ' . $e->getMessage());
        }

        // 记录解密查看日志
        UserLog::record($userId, 'view_decrypted_account', "查看解密账号: {$account->title}", 'account', $accountId);

        // 更新最后使用时间
        $account->updateLastUsed();

        return $accountArray;
    }

    /**
     * 创建账号
     */
    public function createAccount($userId, $data)
    {
        // 验证分类是否存在且属于用户
        if (!empty($data['category_id'])) {
            $category = Category::where('id', $data['category_id'])
                ->where(function ($query) use ($userId) {
                    $query->where('user_id', $userId)
                        ->whereOr('user_id', null);
                })
                ->find();

            if (!$category) {
                throw new Exception('分类不存在');
            }
        }

        // 获取加密方式
        $encryptMethod = $data['encrypt_method'] ?? 'AES-256-GCM';

        // 前端已加密，直接使用传入的加密数据
        // Controller已将username/password/notes重命名为username_encrypted/password_encrypted/notes_encrypted

        // 创建账号数据
        $accountData = [
            'user_id' => $userId,
            'category_id' => $data['category_id'] ?? null,
            'title' => $data['title'],
            'username_encrypted' => $data['username_encrypted'] ?? '',
            'password_encrypted' => $data['password_encrypted'] ?? '',
            'website' => $data['website'] ?? '',
            'notes_encrypted' => $data['notes_encrypted'] ?? '',
            'icon' => $data['icon'] ?? '',
            'tags' => $data['tags'] ?? '',
            'is_favorite' => $data['is_favorite'] ?? 0,
            'encrypt_method' => $encryptMethod,
            'encrypt_version' => '2.0',
            'expires_at' => $data['expires_at'] ?? null,
        ];

        $account = Account::create($accountData);

        // 记录创建日志
        UserLog::record($userId, 'create_account', "创建账号: {$account->title}", 'account', $account->id);

        return $account->toArray();
    }

    /**
     * 更新账号
     */
    public function updateAccount($userId, $accountId, $data)
    {
        $account = Account::where('id', $accountId)
            ->where('user_id', $userId)
            ->find();

        if (!$account) {
            throw new Exception('账号不存在');
        }

        // 验证分类是否存在且属于用户
        if (!empty($data['category_id'])) {
            $category = Category::where('id', $data['category_id'])
                ->where(function ($query) use ($userId) {
                    $query->where('user_id', $userId)
                        ->whereOr('user_id', null);
                })
                ->find();

            if (!$category) {
                throw new Exception('分类不存在');
            }
        }

        // 获取加密方式
        $encryptMethod = $data['encrypt_method'] ?? $account->encrypt_method ?? 'AES-256-GCM';

        // 前端已加密，直接使用传入的加密数据
        // Controller已将username/password/notes重命名为username_encrypted/password_encrypted/notes_encrypted

        // 更新账号数据
        $updateData = [];
        $allowedFields = [
            'category_id', 'title', 'website', 'icon', 'tags', 'is_favorite',
            'encrypt_version', 'expires_at', 'encrypt_method',
            'username_encrypted', 'password_encrypted', 'notes_encrypted'
        ];

        foreach ($allowedFields as $field) {
            if (isset($data[$field])) {
                $updateData[$field] = $data[$field];
            }
        }

        $account->save($updateData);

        // 记录更新日志
        UserLog::record($userId, 'update_account', "更新账号: {$account->title}", 'account', $account->id);

        return $account->toArray();
    }

    /**
     * 删除账号
     */
    public function deleteAccount($userId, $accountId)
    {
        $account = Account::where('id', $accountId)
            ->where('user_id', $userId)
            ->find();

        if (!$account) {
            throw new Exception('账号不存在');
        }

        $title = $account->title;
        $account->delete();

        // 记录删除日志
        UserLog::record($userId, 'delete_account', "删除账号: {$title}", 'account', $accountId);

        return true;
    }

    /**
     * 切换收藏状态
     */
    public function toggleFavorite($userId, $accountId)
    {
        $account = Account::where('id', $accountId)
            ->where('user_id', $userId)
            ->find();

        if (!$account) {
            throw new Exception('账号不存在');
        }

        $account->toggleFavorite();

        $action = $account->is_favorite ? '收藏' : '取消收藏';
        UserLog::record($userId, 'update_account', "{$action}账号: {$account->title}", 'account', $account->id);

        return $account->toArray();
    }

    /**
     * 复制密码（记录日志）
     */
    public function copyPassword($userId, $accountId)
    {
        $account = Account::where('id', $accountId)
            ->where('user_id', $userId)
            ->find();

        if (!$account) {
            throw new Exception('账号不存在');
        }

        // 更新最后使用时间
        $account->updateLastUsed();

        // 记录复制密码日志
        UserLog::record($userId, 'copy_password', "复制密码: {$account->title}", 'account', $account->id);

        return true;
    }

    /**
     * 获取收藏账号
     */
    public function getFavoriteAccounts($userId)
    {
        // 使用预加载避免N+1查询
        $accounts = Account::getFavoriteAccounts($userId)
            ->with(['category'])
            ->select();

        return $accounts->toArray();
    }

    /**
     * 搜索账号
     */
    public function searchAccounts($userId, $keyword)
    {
        if (empty($keyword)) {
            return [];
        }

        // 使用预加载避免N+1查询
        $accounts = Account::searchAccounts($userId, $keyword)
            ->with(['category'])
            ->select();

        return $accounts->toArray();
    }

    /**
     * 获取即将过期的账号
     */
    public function getExpiringAccounts($userId, $days = 7)
    {
        // 使用预加载避免N+1查询
        $accounts = Account::getExpiringAccounts($userId, $days)
            ->with(['category'])
            ->select();

        return $accounts->toArray();
    }

    /**
     * 获取已过期的账号
     */
    public function getExpiredAccounts($userId)
    {
        // 使用预加载避免N+1查询
        $accounts = Account::getExpiredAccounts($userId)
            ->with(['category'])
            ->select();

        return $accounts->toArray();
    }

    /**
     * 批量删除账号
     */
    public function batchDeleteAccounts($userId, $accountIds)
    {
        if (empty($accountIds)) {
            throw new Exception('请选择要删除的账号');
        }

        $accounts = Account::where('user_id', $userId)
            ->whereIn('id', $accountIds)
            ->select();

        if ($accounts->isEmpty()) {
            throw new Exception('未找到要删除的账号');
        }

        $titles = [];
        foreach ($accounts as $account) {
            $titles[] = $account->title;
        }

        // 执行删除
        Account::where('user_id', $userId)
            ->whereIn('id', $accountIds)
            ->delete();

        // 记录删除日志
        UserLog::record($userId, 'delete_account', "批量删除账号: " . implode(', ', $titles));

        return count($titles);
    }

    /**
     * 批量更新分类
     */
    public function batchUpdateCategory($userId, $accountIds, $categoryId)
    {
        if (empty($accountIds)) {
            throw new Exception('请选择要更新的账号');
        }

        // 验证分类
        if ($categoryId) {
            $category = Category::where('id', $categoryId)
                ->where(function ($query) use ($userId) {
                    $query->where('user_id', $userId)
                        ->whereOr('user_id', null);
                })
                ->find();

            if (!$category) {
                throw new Exception('分类不存在');
            }
        }

        // 执行更新
        $count = Account::where('user_id', $userId)
            ->whereIn('id', $accountIds)
            ->update(['category_id' => $categoryId]);

        // 记录更新日志
        $categoryName = $categoryId ? $category->name : '无分类';
        UserLog::record($userId, 'update_account', "批量更新账号分类为: {$categoryName}");

        return $count;
    }

    /**
     * 获取用户账号统计信息
     */
    public function getUserAccountStats($userId)
    {
        return Account::getUserAccountStats($userId);
    }

    /**
     * 导出账号数据
     */
    public function exportAccounts($userId, $categoryId = null)
    {
        $query = Account::where('user_id', $userId);

        if ($categoryId) {
            $query->where('category_id', $categoryId);
        }

        // 使用预加载避免N+1查询
        $accounts = $query->with(['category'])->select();

        // 记录导出日志
        UserLog::record($userId, 'export_data', '导出账号数据');

        return $accounts->toArray();
    }
}